package com.zscat.mallplus.service.pms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.entity.vo.pms.*;
import com.zscat.mallplus.pms.entity.*;
import com.zscat.mallplus.pms.mapper.*;
import com.zscat.mallplus.pms.vo.HomeProductInfo;
import com.zscat.mallplus.service.pms.service.IPmsProductConsultService;
import com.zscat.mallplus.util.HttpClientUtil;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.vo.PageInfo;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 产品咨询表 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-04-19
 */
@Service
public class PmsProductConsultServiceImpl extends ServiceImpl<PmsProductConsultMapper, PmsProductConsult> implements IPmsProductConsultService {


    @Resource
    private PmsGoodsServiceMapper pmsGoodsServiceMapper;

    @Resource
    private PmsProductCategoryMapper pmsProductCategoryMapper;

    @Resource
    private PmsSkuStockMapper pmsSkuStockMapper;

    @Resource
    private PmsProductConsultMapper pmsProductConsultMapper;

    @Resource
    private PmsProductPraiseMapper pmsProductPraiseMapper;

    @Resource
    private PmsProductReplyMapper pmsProductReplyMapper;


    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");


    @Override
    public List<PrimaryClassification> getAllGoodsType() {
        List<PrimaryClassification> primaryClassifications = new ArrayList<>();
        List<PrimaryClassification> result = new ArrayList<>();

        List<PmsProductCategory> level = findPrimaryClassification("level", 0);


        if (level.size() > 0) {

            for (PmsProductCategory pmsProductCategory : level) {
                PrimaryClassification primaryClassification = new PrimaryClassification();
                Long id = pmsProductCategory.getId();

                primaryClassification.setId(id);
                primaryClassification.setBannerImg(pmsProductCategory.getBannerImg());
                primaryClassification.setName(pmsProductCategory.getName());
                primaryClassification.setParentId(pmsProductCategory.getParentId());
                primaryClassifications.add(primaryClassification);
            }
        } else {
//            return null;
        }


        for (PrimaryClassification primaryClassification : primaryClassifications) {
            Long id = primaryClassification.getId();

            List<SecondaryClassification> secondaryClassificationList = new ArrayList<>();

            List<PmsProductCategory> secondaryClassification = findSecondaryClassification("parent_id", id, "level", 1);

            for (PmsProductCategory pmsProductCategory : secondaryClassification) {
                SecondaryClassification secondaryClassification1 = new SecondaryClassification();
                secondaryClassification1.setId(pmsProductCategory.getId());
                secondaryClassification1.setIcon(pmsProductCategory.getIcon());
                secondaryClassification1.setName(pmsProductCategory.getName());
                secondaryClassificationList.add(secondaryClassification1);
            }

            primaryClassification.setSecondaryClassification(secondaryClassificationList);

        }

        for (PrimaryClassification primaryClassification : primaryClassifications) {
            List<SecondaryClassification> secondaryClassification = primaryClassification.getSecondaryClassification();

            for (SecondaryClassification classification : secondaryClassification) {
                List<TertiaryClassification> tertiaryClassificationList = new ArrayList<>();

                Long id = classification.getId();

                List<PmsProductCategory> secondaryClassification1 = findSecondaryClassification("parent_id", id, "level", 2);

                for (PmsProductCategory pmsProductCategory : secondaryClassification1) {
                    TertiaryClassification tertiaryClassification = new TertiaryClassification();

                    tertiaryClassification.setId(pmsProductCategory.getId());
                    tertiaryClassification.setName(pmsProductCategory.getName());
                    tertiaryClassification.setIcon(pmsProductCategory.getIcon());

                    tertiaryClassificationList.add(tertiaryClassification);
                }

                classification.setTertiaryClassification(tertiaryClassificationList);
            }
        }


        for (int i = 0; i < primaryClassifications.size(); i++) {

            List<SecondaryClassification> secondaryClassification = primaryClassifications.get(i).getSecondaryClassification();

            for (int j = 0; j < secondaryClassification.size(); j++) {
                List<TertiaryClassification> tertiaryClassificationList = new ArrayList<>();

                List<TertiaryClassification> tertiaryClassification = secondaryClassification.get(j).getTertiaryClassification();

                if (tertiaryClassification.size() == 0) {

                    TertiaryClassification tertiaryClassification1 = new TertiaryClassification();
                    tertiaryClassification1.setId(secondaryClassification.get(j).getId());
                    tertiaryClassification1.setIcon(secondaryClassification.get(j).getIcon());
                    tertiaryClassification1.setName(secondaryClassification.get(j).getName());

                    secondaryClassification.get(j).setName("");

                    tertiaryClassificationList.add(tertiaryClassification1);

                    secondaryClassification.get(j).setTertiaryClassification(tertiaryClassificationList);
                }
            }
        }

        for (int i = 0; i < primaryClassifications.size(); i++) {
            List<SecondaryClassification> secondaryClassification = primaryClassifications.get(i).getSecondaryClassification();
            List<TertiaryClassification> secondaryClassificationList = new ArrayList<>();
            //记录第一个list 中name为空的

            int id = -1;

            for (int j = 0; j < secondaryClassification.size(); j++) {
                if (!StringUtils.isEmpty(secondaryClassification.get(j).getName())) {
                    break;
                } else {
                    List<TertiaryClassification> tertiaryClassification = secondaryClassification.get(j).getTertiaryClassification();
                    secondaryClassificationList.addAll(tertiaryClassification);
                    if (id == -1) {
                        id = j;
                    }
                }
                secondaryClassification.get(id).setTertiaryClassification(secondaryClassificationList);
            }

            if (id != -1) {
                secondaryClassification.get(id).setName("1");
            }
        }

        for (int i = 0; i < primaryClassifications.size(); i++) {
            List<SecondaryClassification> secondaryClassification = primaryClassifications.get(i).getSecondaryClassification();

            for (int j = 0; j < secondaryClassification.size(); j++) {
                String name = secondaryClassification.get(j).getName();

                if (StringUtils.isEmpty(name)) {
                    secondaryClassification.remove(j);
                }
            }
        }

        for (int i = 0; i < primaryClassifications.size(); i++) {
            List<SecondaryClassification> secondaryClassification = primaryClassifications.get(i).getSecondaryClassification();

            for (int j = 0; j < secondaryClassification.size(); j++) {
                String name = secondaryClassification.get(j).getName();

                if (name.equals("1")) {
                    secondaryClassification.get(j).setName("");
                }
            }
        }

        return primaryClassifications;
    }


    @Override
    public void getAllGoodsTypes() {
        //一级分类
        List<PmsProductCategory> primaryClassification = new ArrayList<>();
        List<PmsProductCategory> pmsProductCategories = pmsProductCategoryMapper.selectList(null);

        for (PmsProductCategory pmsProductCategory : pmsProductCategories) {
            Integer level = pmsProductCategory.getLevel();
            if (level == 0) {
                primaryClassification.add(pmsProductCategory);
            }
        }
    }

    @Override
    public List<Object> combination(Long id) {

        QueryWrapper<PmsSkuStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", id);
        List<PmsSkuStock> pmsSkuStocks = pmsSkuStockMapper.selectList(queryWrapper);
        List<Object> result = new ArrayList<>();
        for (PmsSkuStock pmsSkuStock : pmsSkuStocks) {
            String pic = "";

            Combination combination = new Combination();
            combination.setId(pmsSkuStock.getId());
            combination.setPic(pmsSkuStock.getPic());
            combination.setPrice(pmsSkuStock.getPrice());
            combination.setStock(pmsSkuStock.getStock());
            String sp1 = pmsSkuStock.getSp1();
            String sp2 = pmsSkuStock.getSp2();
            String sp3 = pmsSkuStock.getSp3();
            if (!StringUtils.isEmpty(sp1)) {
                pic = sp1;

                if (!StringUtils.isEmpty(sp2)) {
                    pic = pic + "+" + sp2;
                }
                if (!StringUtils.isEmpty(sp3)) {
                    pic = pic + "+" + sp3;
                }
            }
            combination.setSp1(pic);
            result.add(combination);
        }

        return result;
    }

    @Override
    public List<PmsGoodsService> getGoodsService(String ids) {
        List<PmsGoodsService> result = new ArrayList<>();

        if (!StringUtils.isEmpty(ids)) {

            String[] split = ids.split(",");

            for (String id : split) {
                PmsGoodsService pmsGoodsService = pmsGoodsServiceMapper.selectById(id);
                result.add(pmsGoodsService);
            }
            return result;
        } else {
            return result;
        }
        //pmsGoodsServiceMapper
    }

    @Override
    public PageInfo<PmsProductConsult> getGoodsEvaluation(Long goodsId, Long inquireType, Integer pageNum, Integer pageSize) {
        List<PmsProductConsult> productConsults = null;

        if (inquireType == 0) {
            productConsults = findGoodsEvaluation("goods_id", goodsId, pageNum, pageSize);
        } else if (inquireType == 1) {
            productConsults = findGoodsEvaluationNe("goods_id", goodsId, "images", "", pageNum, pageSize);
        } else if (inquireType == 2) {
            productConsults = findGoodsEvaluation("goods_id", goodsId, "stars", 3, pageNum, pageSize);
        } else if (inquireType == 3) {
            productConsults = findGoodsEvaluation("goods_id", goodsId, "stars", 2, pageNum, pageSize);
        } else if (inquireType == 4) {
            productConsults = findGoodsEvaluation("goods_id", goodsId, "stars", 1, pageNum, pageSize);
        } else {
            productConsults = findGoodsEvaluation("goods_id", goodsId, pageNum, pageSize);
        }
        return new PageInfo<>(pageNum, pageSize, productConsults);
    }

    @Override
    public PageInfo<PmsProductConsultVo> isPraise(Integer pageNum, Integer pageSize, Long memberId, List<PmsProductConsultVo> goodsEvaluation) {
        boolean flag = false;
        List<PmsProductConsultVo> result = new ArrayList<>();

//        List<PmsProductConsult> recordList = goodsEvaluation.getRecordList();

        if (goodsEvaluation.size() > 0) {
            for (PmsProductConsultVo pmsProductConsult : goodsEvaluation) {

//                PmsProductConsultVo pmsProductConsultVo = new PmsProductConsultVo();

                if (memberId != null) {
                    PmsProductPraise memberPraise = findMemberPraise("reply_id", pmsProductConsult.getId(), "member_id", memberId);

                    if (memberPraise != null) {
                        flag = true;
                    }
                }
//                BeanUtils.copyProperties(pmsProductConsult, pmsProductConsultVo);
                StringBuilder stringBuffer = new StringBuilder("");

                if (pmsProductConsult.getIsanonymous()) {
                    String memberName = pmsProductConsult.getMemberName();

                    String[] split = memberName.split("");

                    stringBuffer.append(split[0]);
                    stringBuffer.append("*");
                    stringBuffer.append("*");
                    stringBuffer.append("*");
                    stringBuffer.append(split[split.length - 1]);
                }

//                String images = pmsProductConsult.getImages();

//                if (!StringUtils.isEmpty(images)) {
//                    String[] split = images.split(",");
//                    pmsProductConsultVo.setImages(split);
//                } else {
//                    pmsProductConsultVo.setImages(new String[0]);
//                }

                List<PmsProductReply> reply = findReplyCount("reply_id", pmsProductConsult.getId());

                pmsProductConsult.setIsPraise(flag);
                pmsProductConsult.setCommentNumber(reply.size());
                pmsProductConsult.setMemberName(stringBuffer.toString());
//                pmsProductConsultVo.setConsultAddtime(simpleDateFormat.format(pmsProductConsult.getConsultAddtime()));

                result.add(pmsProductConsult);
            }

        }
        return new PageInfo<>(pageNum, pageSize, result);
    }

    @Override
    public List<PmsProductConsultVo> getNodeConsult(PageInfo<PmsProductConsult> goodsEvaluation) {
        List<PmsProductConsultVo> result = new ArrayList<>();

        List<PmsProductConsult> recordList = goodsEvaluation.getRecordList();

        if (recordList.size() == 0) {
            return null;
        }

        for (PmsProductConsult pmsProductConsult : recordList) {

            PmsProductConsultVo pmsProductConsultVo = new PmsProductConsultVo();
            Long id = pmsProductConsult.getId();

            PmsProductReply nodeConsult = findNodeConsult("reply_id", id, "type", 1);

            if (nodeConsult != null) {
                pmsProductConsultVo.setTreasurer(nodeConsult.getContent());
            } else {
                pmsProductConsultVo.setTreasurer("");
            }
            BeanUtils.copyProperties(pmsProductConsult, pmsProductConsultVo);

            String images = pmsProductConsult.getImages();
            pmsProductConsultVo.setConsultAddtime(simpleDateFormat.format(pmsProductConsult.getConsultAddtime()));
            if (!StringUtils.isEmpty(images)) {
                String[] split = images.split(",");
                pmsProductConsultVo.setImages(split);
            } else {
                pmsProductConsultVo.setImages(new String[0]);
            }


            result.add(pmsProductConsultVo);

        }

        return result;
    }

    @Override
    public CommonResult fileUpload(MultipartFile[] files) {

        CommonResult commonResult = new CommonResult();


        Map<String, Object> fileMap = new HashMap<>();
        Map<String, Object> tokenMap = new HashMap<>();

        //调用oss 文件上传
        List<String> fileName = new ArrayList<>();
        //把数组转成集合
        List<MultipartFile> fileList = new ArrayList<>(Arrays.asList(files));

        for (MultipartFile file : files) {
            fileName.add(file.getOriginalFilename());
        }

        tokenMap.put("appId", "cJG3JSr5od9HkN6HJwy9g8ffPOUmfSUFVtdkXovyt5KqZVBiOeKQz0Zp9KmVRzYl");
        tokenMap.put("appSecret", "qVw9mEy7MDK7skv8BXa1mw==");

        String token = getToken(tokenMap);

        //文件上传
        fileMap.put("token", token);
        fileMap.put("appId", "cJG3JSr5od9HkN6HJwy9g8ffPOUmfSUFVtdkXovyt5KqZVBiOeKQz0Zp9KmVRzYl");
        fileMap.put("platformId", "");
        fileMap.put("bucketName", "personal");

        JSONObject jsonObject = agentFileUpload("http://127.0.0.1:8086/file/fileUploadBolg", fileMap, fileName, fileList);

        BolgVo bolgVo;
        try {
            bolgVo = JSONObject.parseObject(jsonObject.get("data").toString(), BolgVo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return commonResult.failed("系统异常");
        }

        List<String> result = new ArrayList<>();
        List<String> successFile = bolgVo.getSuccessFile();

        for (String s : successFile) {
            result.add("http://192.168.1.83:8086/file/" + s);

        }
        bolgVo.setSuccessFile(result);
        return commonResult.success(bolgVo);
    }

    @Override
    public CommonResult videoUpload(MultipartFile file) {
        CommonResult commonResult = new CommonResult();

        Map<String, Object> fileMap = new HashMap<>();
        Map<String, Object> tokenMap = new HashMap<>();

        //调用oss 文件上传
        List<String> fileName = new ArrayList<>();
        //把数组转成集合
        List<MultipartFile> fileList = new ArrayList<>();

        fileList.add(file);

        fileName.add(file.getOriginalFilename());


        tokenMap.put("appId", "cJG3JSr5od9HkN6HJwy9g8ffPOUmfSUFVtdkXovyt5KqZVBiOeKQz0Zp9KmVRzYl");
        tokenMap.put("appSecret", "qVw9mEy7MDK7skv8BXa1mw==");

        String token = getToken(tokenMap);

        //文件上传
        fileMap.put("token", token);
        fileMap.put("appId", "cJG3JSr5od9HkN6HJwy9g8ffPOUmfSUFVtdkXovyt5KqZVBiOeKQz0Zp9KmVRzYl");
        fileMap.put("platformId", "");
        fileMap.put("bucketName", "personal");

        JSONObject jsonObject = agentFileUpload("http://127.0.0.1:8086/file/videoUpload", fileMap, fileName, fileList);

        VideoVo bolgVo;
        try {
            bolgVo = JSONObject.parseObject(jsonObject.get("data").toString(), VideoVo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return commonResult.failed("系统异常");
        }

        List<ImgInfoVo> successFile = bolgVo.getSuccessFile();
        successFile.get(0).setPath("http:192.168.1.83:8086/goods" + successFile.get(0).getPath());
        bolgVo.setSuccessFile(successFile);
        bolgVo.setCover("http:192.168.1.83:8086/goods" + bolgVo.getCover());
        return commonResult.success(bolgVo);


    }

    @Override
    public String fileUpload(String url) {

        CommonResult commonResult = new CommonResult();


        Map<String, Object> fileMap = new HashMap<>();
        Map<String, Object> tokenMap = new HashMap<>();


        tokenMap.put("appId", "cJG3JSr5od9HkN6HJwy9g8ffPOUmfSUFVtdkXovyt5KqZVBiOeKQz0Zp9KmVRzYl");
        tokenMap.put("appSecret", "qVw9mEy7MDK7skv8BXa1mw==");

        String token = getToken(tokenMap);

        //文件上传
        fileMap.put("token", token);
        fileMap.put("appId", "cJG3JSr5od9HkN6HJwy9g8ffPOUmfSUFVtdkXovyt5KqZVBiOeKQz0Zp9KmVRzYl");
        fileMap.put("platformId", "");
        fileMap.put("bucketName", "personal");
        fileMap.put("url", url);


        JSONObject jsonObject = agentFileUpload(fileMap);

        String data = null;
        try {
            data = jsonObject.get("data").toString();

        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }

        return data;
    }


    private String getToken(Map<String, Object> tokenMap) {
        CommonResult commonResult = new CommonResult();
        String tokenResult = HttpClientUtil.postJson("http://127.0.0.1:8084/authoriz/getToken", tokenMap);

        if (StringUtils.isEmpty(tokenResult)) {
            return "1";
        }

        JSONObject tokenJson = JSONObject.parseObject(tokenResult);

        if (!tokenJson.get("code").equals("200")) {
            return "2";
        }

        return tokenJson.get("data").toString();
    }

    private JSONObject agentFileUpload(String url, Map<String, Object> fileMap, List<String> fileName, List<MultipartFile> fileList) {
        String fileResult = HttpClientUtil.httpPostRequest2(url, fileList, fileName, fileMap, 5000);

//        if (StringUtils.isEmpty(fileResult)) {
//            throw new CustomException(ResponseUtil.fall("-9001", "系统异常"));
//        }

        //        if (!fileJson.get("code").equals("200")) {
//            throw new CustomException(ResponseUtil.fall("-9001", "系统异常"));
//        }
        return JSONObject.parseObject(fileResult);
    }

    private JSONObject agentFileUpload(Map<String, Object> fileMap) {
        String fileResult = HttpClientUtil.postJson("http://127.0.0.1:8086/file/compression", fileMap);

//        if (StringUtils.isEmpty(fileResult)) {
//            throw new CustomException(ResponseUtil.fall("-9001", "系统异常"));
//        }

        //        if (!fileJson.get("code").equals("200")) {
//            throw new CustomException(ResponseUtil.fall("-9001", "系统异常"));
//        }
        return JSONObject.parseObject(fileResult);
    }


    private PmsProductReply findNodeConsult(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductReplyMapper.selectOne(queryWrapper);
    }

    private List<PmsProductReply> findReplyCount(String column, Object value) {
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return pmsProductReplyMapper.selectList(queryWrapper);
    }

    private PmsProductPraise findMemberPraise(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductPraise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);

        return pmsProductPraiseMapper.selectOne(queryWrapper);
    }

    private List<PmsProductConsult> findGoodsEvaluation(String column, Object value, String column1, Object value1, Integer pageNum, Integer pageSize) {
        QueryWrapper<PmsProductConsult> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(column, value).eq(column1, value1);

        IPage<PmsProductConsult> page = new Page<>();

        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<PmsProductConsult> pmsProductConsultIPage = pmsProductConsultMapper.selectPage(page, queryWrapper);
        return pmsProductConsultIPage.getRecords();
    }

    private List<PmsProductConsult> findGoodsEvaluationNe(String column, Object value, String column1, Object value1, Integer pageNum, Integer pageSize) {
        QueryWrapper<PmsProductConsult> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(column, value).ne(column1, value1);

        IPage<PmsProductConsult> page = new Page<>();

        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<PmsProductConsult> pmsProductConsultIPage = pmsProductConsultMapper.selectPage(page, queryWrapper);
        return pmsProductConsultIPage.getRecords();
    }


    private List<PmsProductConsult> findGoodsEvaluation(String column, Object value, Integer pageNum, Integer pageSize) {
        QueryWrapper<PmsProductConsult> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(column, value);

        IPage<PmsProductConsult> page = new Page<>();

        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<PmsProductConsult> pmsProductConsultIPage = pmsProductConsultMapper.selectPage(page, queryWrapper);
        return pmsProductConsultIPage.getRecords();
    }


    private List<PmsProductCategory> findPrimaryClassification(String column, Object value) {
        QueryWrapper<PmsProductCategory> queryWrapper = new QueryWrapper<PmsProductCategory>();
        queryWrapper.eq(column, value);
        return pmsProductCategoryMapper.selectList(queryWrapper);
    }

    private List<PmsProductCategory> findSecondaryClassification(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductCategory> queryWrapper = new QueryWrapper<PmsProductCategory>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductCategoryMapper.selectList(queryWrapper);
    }


}
